package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.utils.PermissionHelper;
import com.atguigu.ssyx.model.acl.Permission;
import com.atguigu.ssyx.model.base.BaseEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author：tzl
 * @Date：2023/11/10 16:45
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    /**
     * 获取所有菜单
     * @return
     */
    @Override
    public List<Permission> queryAllMenu() {
        // 获取全部
        List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>()
                .orderByAsc("CAST(id AS SIGNED)"));

        // 获取菜单树结构
        List<Permission> result = PermissionHelper.build(allPermissionList);
        return result;
    }

    /**
     * 删除菜单及其子菜单
     * @param id
     * @return
     */
    @Override
    public boolean removeChildById(Long id) {
        ArrayList<Long> idList = new ArrayList<>();
        // 将此节点id和其孩子节点id收拢到list中
        idList.add(id);
        this.selectChildListById(id, idList);

        // 批量删除
        return this.removeByIds(idList);
    }

    private void selectChildListById(Long id, ArrayList<Long> idList) {
        // 通过父节点查询id
        List<Permission> childIdList = baseMapper.selectList(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getPid, id).select(BaseEntity::getId));

        childIdList.forEach(childId -> idList.add(childId.getId()));
    }


}
